package com.example.jpushdemo;


import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import cn.jpush.android.api.InstrumentedActivity;
import cn.jpush.android.api.JPushInterface;

import com.example.util.ConstantSet;
import com.example.util.FileUtil;
import com.example.util.HttpUtil;


public class MainActivity extends InstrumentedActivity implements OnClickListener{
	private static final String TAG = "MainActivity";
	private Button mInit;
	private Button mSetting;
	private Button mStopPush;
	private Button mResumePush;
	private Button register;
	private EditText msgText;
	
	public static boolean isForeground = false;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		//initView(); 
		Intent i = new Intent(getApplicationContext(),ResStartService.class);
		startService(i);
//		registerMessageReceiver();  // used for receive msg
		Log.d(TAG, "RegistrationID: " + JPushInterface.getRegistrationID(this));
	}
	
	private void initView(){
		TextView mImei = (TextView) findViewById(R.id.tv_imei);
		String udid =  ExampleUtil.getImei(getApplicationContext(), "");
        if (null != udid) mImei.setText("IMEI: " + udid);
        
		TextView mAppKey = (TextView) findViewById(R.id.tv_appkey);
		String appKey = ExampleUtil.getAppKey(getApplicationContext());
		if (null == appKey) appKey = "AppKey异常";
		mAppKey.setText("AppKey: " + appKey);

		String packageName =  getPackageName();
		TextView mPackage = (TextView) findViewById(R.id.tv_package);
		mPackage.setText("PackageName: " + packageName);
		
		String versionName =  ExampleUtil.GetVersion(getApplicationContext());
		TextView mVersion = (TextView) findViewById(R.id.tv_version);
		mVersion.setText("Version: " + versionName);
		
	    mInit = (Button)findViewById(R.id.init);
		mInit.setOnClickListener(this);
		
		mStopPush = (Button)findViewById(R.id.stopPush);
		mStopPush.setOnClickListener(this);
		
		mResumePush = (Button)findViewById(R.id.resumePush);
		mResumePush.setOnClickListener(this);
		
		register = (Button)findViewById(R.id.register);
		register.setOnClickListener(this);
		
		mSetting = (Button)findViewById(R.id.setting);
		mSetting.setOnClickListener(this);
		
		msgText = (EditText)findViewById(R.id.msg_rec);
	}

	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.init:
			init();
			break;
		case R.id.setting:
			Intent intent = new Intent(MainActivity.this, PushSetActivity.class);
			startActivity(intent);
			break;
		case R.id.stopPush:
			JPushInterface.stopPush(getApplicationContext());
			break;
		case R.id.resumePush:
			JPushInterface.resumePush(getApplicationContext());
			break;
		case R.id.register:
			HttpUtil.doPost(ConstantSet.registerUrl.replace("{RegistrationID}", JPushInterface.getRegistrationID(getApplicationContext())), null);
			break;
		}
	}
	
	// 初始化 JPush。如果已经初始化，但没有登录成功，则执行重新登录。
	private void init(){
		 JPushInterface.init(getApplicationContext());
	}


	@Override
	protected void onResume() {
		isForeground = true;
		super.onResume();
	}


	@Override
	protected void onPause() {
		isForeground = false;
		super.onPause();
	}


	@Override
	protected void onDestroy() {
//		unregisterReceiver(mMessageReceiver);
		super.onDestroy();
	}
	

	//for receive customer msg from jpush server
	private MessageReceiver mMessageReceiver;
	public static final String MESSAGE_RECEIVED_ACTION = "com.example.jpushdemo.MESSAGE_RECEIVED_ACTION";
	public static final String KEY_TITLE = "title";
	public static final String KEY_MESSAGE = "message";
	public static final String KEY_EXTRAS = "extras";
	
	public void registerMessageReceiver() {
		mMessageReceiver = new MessageReceiver();
		IntentFilter filter = new IntentFilter();
		filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
		filter.addAction(MESSAGE_RECEIVED_ACTION);
		registerReceiver(mMessageReceiver, filter);
		
	}

	public class MessageReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
              String messge = intent.getStringExtra(KEY_MESSAGE);
              final String extras = intent.getStringExtra(KEY_EXTRAS);
              final StringBuilder showMsg = new StringBuilder();
              showMsg.append(KEY_MESSAGE + " : " + messge + "\n");
//              String url = null;
              if (!ExampleUtil.isEmpty(extras)) {
            	  showMsg.append(KEY_EXTRAS + " : " + extras + "\n");
            	  
            	
            	handler.post(new Runnable() {  
                    @Override  
                    public void run() { 
                    	JSONTokener jsonParser = new JSONTokener(extras); 
                    	JSONObject httpObj = null;
                  	  try {
      					httpObj = (JSONObject) jsonParser.nextValue();
//      					url = httpObj.getString("http");
      					if(null != httpObj.getString("torrent")) {
//      						File extDir = Environment.getExternalStorageDirectory();
      						File extDir = new File(FileUtil.getDownLoadPath());
      						if(extDir.exists()) {
      							String url = httpObj.getString("torrent");
//      							String filename = FileUtil.getUrlFileName(url);
      							String filename = "2014.torrent";
          						File fullFilename = new File(extDir, filename);
          						fullFilename.deleteOnExit();
                          		FileUtil.downlodFile(url, fullFilename.getAbsolutePath(), null);
      						} else {
      							setCostomMsg("DownLoadResult" + " : " + extDir.getAbsolutePath() + " do not exist! \n");
      						}
      						
                      	}
      				} catch (JSONException e) {
      					// TODO Auto-generated catch block
      					e.printStackTrace();
      				} catch (ClientProtocolException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
                  
                }});
            	setCostomMsg(showMsg.toString());
              }
			}
		}
	}
	
	 private Handler handler = new Handler() {  
	        @Override  
	        public void handleMessage(Message msg) {  
	            switch (msg.what) {  
	            case 1:  
	                // 关闭  
	  
	                break;  
	            }  
	        }  
	    };  
	
	private void setCostomMsg(String msg){
		 if (null != msgText) {
//			 msgText.setText(msg);
			 msgText.append(msg);
			 msgText.setVisibility(android.view.View.VISIBLE);
         }
	}

}